package com.youle.upload.controller;

import com.youle.enums.ExceptionEnum;
import com.youle.exception.YLException;
import com.youle.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Created by
 *  处理文件图片等上传的controller  在此处进行文件的校验等操作
 * @author touni
 * @date 2019/4/19
 * @time 10:46
 */
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {

    //定义一个支持的文件类型的list
    private static final List<String> supportFileType = Arrays.asList("image/png","image/jpg","image/jpeg");

    @Autowired
    private UploadService uploadService;


    @PostMapping("image")
    public ResponseEntity<String> uploadFile(MultipartFile file){
        //判断是否有文件
        if (null == file){
            throw new YLException(ExceptionEnum.UPLOAD_PARA_ERROR);
        }
        InputStream inputStream = null;
        //获取图片的类型 和内容  校验文件
        try {
            String contentType = file.getContentType();
            inputStream = file.getInputStream();
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            if (!supportFileType.contains(contentType) || null == bufferedImage) {
                log.info("上传文件不支持 时间：" + System.currentTimeMillis());
                throw new YLException(ExceptionEnum.UPLOAD_PARA_ERROR);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("读取文件流或者内容失败 时间："+System.currentTimeMillis(),e);
            throw new YLException(ExceptionEnum.UPLOAD_PARA_ERROR);
        }

        return uploadService.uploadFile(file);


    }


}
